package com.example.pingze.controller;

import com.example.pingze.entity.MyInfo;
import com.example.pingze.exception.PingZeException;
import com.example.pingze.utils.RedisCache;
import com.example.pingze.utils.ResultVOUtils;
import com.example.pingze.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 搜索历史记录
 * 通过redis缓存
 */
@RestController
@RequestMapping("/history")
@CrossOrigin(origins = "*")
public class HistoricRecordsController {
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 历史记录：通过用户账号，查询其在redis中的历史搜索
     * @param myInfo
     * @return
     */
    @PostMapping("/select")
    public Result<List<String>> select(@RequestBody MyInfo myInfo){
        if(myInfo.getAccount() == null){
            throw new PingZeException("用户账号为空，请先登录!!!");
        }
        List<String> searchList = new ArrayList<>();
        //key
        String key = "history:" + myInfo.getAccount();
        long start = 0;
        long size = 9;
        Set<ZSetOperations.TypedTuple<String>> scoreWithScores = redisTemplate.opsForZSet()
                .rangeWithScores(key, start, size);
        if (scoreWithScores != null && !scoreWithScores.isEmpty()) {
            for (ZSetOperations.TypedTuple<String> tuple : scoreWithScores) {
                searchList.add(tuple.getValue());
            }
        }
        return ResultVOUtils.result(searchList);
    }
}
